function fillAcegiRoles(oid) {
	var container = $("#"+oid);
    var psecu = $("#primarySecu");
	container.empty();
	if (oid == 'undefined' || oid == '')
		return;
	else {
		$.getJSON("admin/securole/secu-role!byuser",{"user.username":username}
		,function(idata,itextStatus,ijqXHR){
			var iaus = idata;
			$.each(iaus,function(sidx,sitem){
				var opt = $("<option></option>").val(sitem.name).text(sitem.description);
				if(psecuName==sitem.name)opt.attr("selected",true);
				psecu.append(opt);
			});
			$.getJSON( 
			    "admin/securole/secu-role!gets",
				function(data,textStatus,jqXHR) {
					$.each(data, function(idx, item) {
						var opt = $("<option></option>");
						opt.val(item.name);
						opt.text(item.description);
						$.each(iaus,function(jdx,jitem){
							if(item.name==jitem.name){
								opt.attr("selected",true);
							    return;
							}							
						});
                		container.append(opt);
					  }
					);
				}
			);
			
		})
		
	}
}

function fillDepartments(oid) {
	var tid = deptId;
	var container = $("#"+oid);
	container.empty();
	if (oid == 'undefined' || oid == '')
		return;
	else {
		$.getJSON(
			"admin/department/department!gets",
			function(data, textStatus, jqXHR) {
				$.each(data, function(idx, item) {
					var opt = $("<option></option>");
					opt.val(item.id);
					opt.text(item.name);
					opt.attr("selected", item.id == tid);
					container.append(opt);
				});
			}
		);
	}
}

function fillRoles(oid) {
	var tid = roleId;
	var container = $("#"+oid);
	container.empty();
	if (oid == 'undefined' || oid == '')
		return;
	else {
		$.getJSON(
			"admin/role/role!gets",
			function(data, textStatus, jqXHR) {
				$.each(data, function(idx, item) {
					var opt = $("<option></option>");
					opt.val(item.id);
					opt.text(item.name);
					opt.attr("selected", item.id == tid);
					container.append(opt);
				});
		    }
		);
	}
}
$(function() {
	fillAcegiRoles('authName');
	fillRoles('roleId');
	fillDepartments('deptId');
	$("#saveBtn").click(function(){
		saveuser();
	}).button()
});
function saveuser() {
	var auths = $("#authName").val() == null ? [] : $("#authName").val();
	var postdata = '';
	postdata += "bean.username=" + $("#username").val();
	postdata += "&bean.localName=" + $("#localName").val();
	postdata += "&bean.password=" + $("#password").val();
	postdata += "&bean.repassword=" + $("#repassword").val();
	postdata += "&bean.department.id=" + $("#deptId").val();
	postdata += "&bean.role.id=" + $("#roleId").val();
	postdata += "&bean.enabled=false";
	var authindex = 0;
	$.each(auths, function(i, e) {
		postdata += "&bean.authoritys[" + (authindex++) + "].name=" + e;
	});
	
	var psecu = $("#primarySecu");
	if(psecu.val()== undefined){
		postdata += "&bean.primarySecurole.name="+auths[0];
	}else{
		postdata += "&bean.primarySecurole.name="+psecu.val();
	}
	if(auths.length==0 && psecu.val()==''){
		alert("请设置权限!");
		return ;
	}
	var url = "admin/user/user!"+act;
	doPost(url,postdata);	
}